/*
 * @Author: Zhouhai 497675647@qq.com
 * @Date: 2022-11-30 11:27:09
 * @LastEditors: 周海 zhouhaib@yonyou.com
 * @LastEditTime: 2022-12-14 18:16:16
 */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { removeUser, addUser, updateUser } from '@/api/system/user';
import BillCard from '@/components/BillCard';
import { useStore } from '@/store';
import { UserDomain } from '@/type.d/system';
import { ProFormColumnsType, ProFormInstance } from '@ant-design/pro-components';
import { Space, Button, Modal, Form, Row, Col, Input, Radio } from 'antd';
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react'
import './index.less';

interface UserCardProp {
    userStatusOptions: any[];
    /**
     * 卡片数据 受控
     */
    cardData: UserDomain;

    newdata?: UserDomain;
    /**
     * 列表数据
     */
    tableListDataSource: UserDomain[];
    /**
     * 更新列表数据
     */
    setTableListDataSource: (data: UserDomain[]) => void;

    isedit?: boolean;

    setIsedit?: (isedit: boolean) => void
    /**
     * 跳转到列表状态
     */
    onBack?: (e?: React.MouseEvent<HTMLElement>) => void;
}
export type UserCardInstance = {
    setIsedit: (isedit: boolean) => void
}
type UserCardRef = React.MutableRefObject<UserCardInstance | undefined> | React.RefObject<UserCardInstance | undefined>

const UserCard = forwardRef((props: UserCardProp) => {
    const { userStatusOptions, cardData, newdata = {}, tableListDataSource, setTableListDataSource, setIsedit, isedit = false, onBack } = props;
    const { layoutStore, userStore } = useStore();
    const [selectdata, setSelectdata] = useState<UserDomain>(cardData);
    const [oldSelectdata, setOldSelectdata] = useState<UserDomain>({});//编辑状态临时保存选中的菜单树数据
    const [formRef] = Form.useForm<UserDomain>();


    const intCardData = (_cardData: UserDomain) => {
        setSelectdata(_cardData)
        setOldSelectdata({})
    }

    const addCardData = (_cardData: UserDomain) => {
        setSelectdata(_cardData)
        setOldSelectdata({ ...selectdata })
        setIsedit?.(true)
    }

    const editCardData = () => {
        setOldSelectdata({ ...selectdata })
        setIsedit?.(true)
    }

    const resetCardData = () => {
        setSelectdata({ ...oldSelectdata })
        setOldSelectdata({})
    }

    const onDelete = (dedata: UserDomain) => {
        if (dedata.userId) {
            layoutStore.OpenSpanning()
            removeUser(dedata.userId).then(() => {
                setSelectdata({})
                setOldSelectdata({})
                setTableListDataSource(tableListDataSource.filter((item) => {
                    return item.userId !== dedata.userId
                }))
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }
    }

    useEffect(() => {//从列表跳转到卡片，如果数据发生了变化，更新数据
        intCardData(cardData)
    }, [cardData])

    useEffect(() => {
        formRef.resetFields()
        if (selectdata) {
            formRef.setFieldsValue({ ...selectdata });
        } else {
            formRef.setFieldsValue({});
        }
    }, [selectdata])

    /**
    * 表单字段配置
    */
    const cardItems: JSX.Element =
        <Row>
            <Col md={8} xl={6}>
                <Form.Item name="nickName" label="用户昵称">
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="phonenumber" label="手机号码">
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="email" label="邮箱" rules={[
                    {
                        type: 'email',
                        message: '输入的邮箱格式不正确！',
                    }
                ]}>
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="userName" label="用户名称">
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6} hidden>
                <Form.Item name="password" label="用户密码" hidden>
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="sex" label="用户性别">
                    <Radio.Group options={[{
                        label: '男',
                        value: '0',
                    },
                    {
                        label: '女',
                        value: '1',
                    },
                    {
                        label: '未知',
                        value: '2',
                    }]
                    } />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="status" label="用户状态">
                    <Radio.Group options={userStatusOptions} />
                </Form.Item>
            </Col>
            <Col md={24} xl={24}>
                <Form.Item name="remark" label="备注">
                    <Input.TextArea />
                </Form.Item>
            </Col>
        </Row>;

    const cardbuttons = (
        <Space>
            <Button
                hidden={!userStore.hasPerms('system:user:add')}
                size='small'
                key="add"
                type="primary"
                onClick={() => {
                    addCardData({ ...newdata })
                }}
            >
                新增
            </Button>
            <Button
                hidden={!userStore.hasPerms('system:user:edit')}
                size='small'
                key="edit"
                type="primary"
                disabled={selectdata?.userId ? false : true}
                onClick={() => {
                    editCardData()
                }}
            >
                修改
            </Button>
            <Button
                hidden={!userStore.hasPerms('system:user:remove')}
                size='small'
                key="delete"
                type="primary"
                disabled={selectdata?.userId ? false : true}
                onClick={() => {
                    Modal.confirm({
                        okText: '确定',
                        cancelText: '取消',
                        title: '系统提示',
                        content: '确定要删除数据吗？',
                        type: 'warning',
                        onOk: () => {
                            onDelete(selectdata)
                        }
                    }
                    )

                }}
            >
                删除
            </Button>
        </Space>
    )

    const onSave = () => {
        formRef.validateFields().then((data) => {
            if (!selectdata.userId) {//新增
                layoutStore.OpenSpanning()
                addUser({ ...selectdata, ...data }).then((res) => {
                    intCardData(res.data)//更新卡片数据

                    tableListDataSource.push(res.data)
                    setTableListDataSource([...tableListDataSource])//更新列表数据

                    setIsedit?.(false)
                }).finally(() => {
                    layoutStore.CloseSpanning()
                })
            } else {//更新
                layoutStore.OpenSpanning()
                updateUser({ ...selectdata, ...data }).then((res) => {
                    intCardData(res.data)//更新卡片数据
                    //更新列表数据
                    setTableListDataSource(tableListDataSource.map((item) => {
                        if (item.userId === res.data.userId) {
                            return res.data
                        } else {
                            return item
                        }
                    }))
                    setIsedit?.(false)
                }).finally(() => {
                    layoutStore.CloseSpanning()
                })
            }
        })

    }

    const editbuttions = (<Space>
        <Button
            size='small'
            key="save"
            type="primary"
            onClick={() => {
                onSave()
            }}
        >
            保存
        </Button>
        <Button
            size='small'
            key="cancel"
            type="primary"
            onClick={() => {
                resetCardData()
                setIsedit?.(false)
            }}
        >
            取消
        </Button>
    </Space>)

    return (
        <BillCard
            formid='userId'
            key={'userCard'}
            formRef={formRef}
            isedit={isedit}
            extraButton={isedit ? editbuttions : cardbuttons}
            onBack={onBack}
            title={'用户管理'}
            cardItem={cardItems}
        />
    )
})
export default UserCard;